import React from "react";
import Divider from "antd/lib/divider";
import Button from "antd/lib/button";
import Modal from 'antd/lib/modal';
import Col from "antd/lib/col";
import zhCN from 'antd/es/locale/zh_CN';
import Row from "antd/lib/row";
import Table from "antd/lib/table";
import Layout from "antd/lib/layout";
import ConfigProvider from "antd/lib/config-provider";
import ProjectDetail from "@/services/projectdetail";
import { AppstoreFilled } from "@ant-design/icons";
import CreateQueryShowFieldDialog from "@/components/enums/QueryShowFieldDialog";
import Dropdown from "antd/lib/dropdown";
import Menu from "antd/lib/menu";
import CreateProjectDetailDialog from "@/components/project/ProjectDetailDialog";
import { currentUser } from "@/services/auth";
import QueryShowField from "@/services/queryshowfield";
import notification from "@/services/notification";
import { get } from "lodash";
import WarningOutlined from "@ant-design/icons/WarningOutlined";
import CheckDialog from "@/components/workflow/CheckDialog";
import Workflow from "@/services/workflow";
import moment from "moment";
import { inject, observer } from 'mobx-react';

const { confirm } = Modal;
const getRowClassName = (record, index) => {
  let className = '';
  if (index % 2 === 0) className = "oddRow";
  return className
}
 class ProjectDetailList extends React.Component {
  state = {
    loading: true,
    page: 1,
    pagesize: 15,
    total: 1,
    order: 1,
    data: [],//跟进列表
    queryshowfielddata: [],
  };
  componentWillMount() {
    this.fieldsshowload();
    this.refreshData({ projectid: this.props.projectStore.projectModel.id, page: 1, pagesize: 15 });
  }
  fieldsshowload = () => {
    QueryShowField.getbycode("projectdetaillist1").then(data => {
      this.setState({
        queryshowfielddata: data,
      });
    });
  }
  refreshData = (params = {}) => {
    this.setState({ loading: true });
    ProjectDetail.getlist(params).then(data => {
      this.setState({
        loading: false,
        data: data.data,
        page: params.page,
        pagesize: params.pagesize,
        total: data.total,
        field: params.field,
        order: params.order,
      });
    });
  };
  handleTableChange = (pagination, filters, sorter) => {
    let field = sorter.field;
    let order = 0;
    if (sorter.order === "descend") {
      order = 1;
    }
    let param = {
      field: field,
      order: order,
      page: pagination.current,
      pagesize: this.state.pagesize,
      projectid: this.props.projectStore.projectModel.id,
    }
    this.refreshData(param);
  };
  handlefieldshow = () => {
    CreateQueryShowFieldDialog.showModal({ queryshowfield: this.state.queryshowfielddata })
      .onClose((result = {}) => {
        if (result.success) {
          this.fieldsshowload();
        }
      }).onDismiss(() => {
      });
  }
  handleadd = () => {
    if(this.props.projectStore.projectModel.bytstatus==="完结"){
      notification.error("项目已完结，不能操作.");
      return;
    }
    CreateProjectDetailDialog.showModal({ data: this.props.projectStore.projectModel })
      .onClose((result = {}) => {
        if (result.success) {
          this.refreshData({ projectid: this.props.projectStore.projectModel.id, page: 1, pagesize: 15 });
        }
      }).onDismiss(() => {
      });
  }
  handleCheck = (record) => {
    if (!currentUser.isAudit) {
      notification.error("没有权限.");
      return;
    }
    let item = {
      bill: "projectdetail",
      billtype: 0,
      billid: record.id,
      next_type: 1,
      message: '<div>同意</div>',
      userid: currentUser.id,
      billdate: moment().format('YYYY-MM-DD'),
      orgunitid: record.orgunitid,
      status: record.status,
    }
    if (record.status === 0) {

      Workflow.check(item).then(data => {
        if (data[0].flag === 0) {
          this.refreshData({ projectid: this.props.projectStore.projectModel.id, page: 1, pagesize: 15 });
          notification.success(data[0].message);
        } else {
          notification.error(data[0].message);
        }
      })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    } else {
      CheckDialog.showModal({ bill_check: item })
        .onClose((result = {}) => {
          if (result.success) {
            this.refreshData({ projectid: this.props.projectStore.projectModel.id, page: 1, pagesize: 15 });
          }
        }).onDismiss(() => {
        });
    }
  };
  handledel = (record) => {
    if (record.status !== 0) {
      notification.error("不是草稿状态，不能删除！");
      return;
    }
    confirm({
      title: '确定删除挂靠人员?',
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        ProjectDetail.delete({ id: record.id }).then(() => {
          notification.success("删除成功.");
          this.refreshData({ projectid: this.props.projectStore.projectModel.id, page: 1, pagesize: 15 });
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  render() {
    const paginationProps = {
      showSizeChanger: true,
      total: this.state.total, // 数据总数
      pageSize: parseInt(this.state.pagesize), // 每页条数
      current: parseInt(this.state.page), // 当前页码
      pageSizeOptions: ["10", "15", "30", "100"],
      showTotal: ((total) => {
        return `共 ${total} 条`;
      }),
    };
    let listcolumns = [];
    if (this.state.queryshowfielddata.fieldsshow !== undefined) {
      (this.state.queryshowfielddata.fieldsshow || []).map(item => {
        let items = this.state.queryshowfielddata.fieldsall.filter((p) => {
          return p.key === item;
        });
        if (items.length > 0) {
          listcolumns.push({
            title: items[0].title,
            dataIndex: item,
            key: item,
            sorter: (a, b) => a[item] > b[item] ? 1 : -1
          })
        }
        return item;
      }
      );
    }
    listcolumns.push({
      title: '操作',
      key: 'action',
      render: (record) => (
        <span>
          <Button size="small">
            <a className="clickable" onClick={() => this.handleCheck(record)}>{record.status === 0 ? "审核" : (record.status === 1 ? "审核中" : "已审核")}</a>
          </Button>&nbsp;&nbsp;
          <Button size="small" disabled={record.status !== 0}>
            <a className="clickable" onClick={() => this.handledel(record)} >{"删除"}</a>
          </Button>
        </span>
      ),
    });
    return (
      <ConfigProvider locale={zhCN}>
        <Layout>
          <Layout style={{ padding: '0 24px 24px' }}>
            <Row style={{ marginBottom: 5 }}>
              <Col span={10}>
                <Button type="primary" onClick={() => this.handleadd()} disabled={this.props.projectStore.projectModel.neednum <= this.state.data.length}>
                  关联人才
                </Button>
                <Divider type="vertical" />
                <Dropdown
                  trigger={["click"]}
                  overlay={
                    <Menu>
                      <Menu.Item key="employee">
                        <a href="employeeproject/new/0" >新增人才</a>
                      </Menu.Item>
                      {currentUser.hasPermission("fieldshow") && (
                        <Menu.Item key="delete-item">
                          <a onMouseUp={() => this.handlefieldshow()}>显示隐藏列</a>
                        </Menu.Item>
                      )}
                    </Menu>
                  }>
                  <Button type="primary" style={{ margin: "10px" }} data-test="CreateButton" >
                    <AppstoreFilled />更多功能
                  </Button>
                </Dropdown>
              </Col>
            </Row>
            <div>
              <Table rowKey='id'
                rowClassName={(record, index) => getRowClassName(record, index)}
                columns={listcolumns}
                scroll={{ x: 'max-content' }}
                dataSource={this.state.data}
                pagination={paginationProps}
                loading={this.state.loading}
                onChange={this.handleTableChange}
              />
            </div>
          </Layout>
        </Layout>
      </ConfigProvider>
      // </Modal>
    );
  }
}
export default inject('projectStore')(observer(ProjectDetailList));